package com.ivan.stu.notetool.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ScreenUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.ivan.stu.notetool.R;
import com.ivan.stu.notetool.callback.ItemClickListener;
import com.ivan.stu.notetool.model.NoteBean;
import com.ivan.stu.notetool.utils.ConstrantManager;
import com.ivan.stu.notetool.utils.HtmlUtil;
import com.ivan.stu.notetool.utils.StringUtil;


import java.util.List;

/**
 * Created by IVAN on 2018/7/4.
 */

public class NoteAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    public List<NoteBean> noteList;
    Context mContext;
    String mCurrentSysName = "";
    public FooterHolder mFooterHolder;
    private ItemClickListener mItemClickListener;
    private String mKeyword = "";
    private boolean mIsScrolling = false;

    public NoteAdapter(Context context, List<NoteBean> noteList){
        this.mContext = context;
        this.noteList = noteList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == 1){  //脚部

            View  itemView = LayoutInflater.from(mContext).inflate(R.layout.foot_layout,parent,false);
            mFooterHolder = new FooterHolder(itemView);
            return mFooterHolder;

        }else if (viewType == 0){  //普通笔记类型

            View  itemView;

            if(ConstrantManager.currentSystemid.equals("b30")){

                itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout_card,parent,false);

            }else {

                itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout,parent,false);
            }

          //  View  itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout,parent,false);


            return new MyViewHolder(itemView);

        }else if (viewType == 2){  //时间标签

            View  itemView = LayoutInflater.from(mContext).inflate(R.layout.time_header_note_layout,parent,false);
            return new TimeViewHolder(itemView);
        }else if (viewType == 6){  //纯文本

            View  itemView;

            if(ConstrantManager.currentSystemid.equals("b30")){

                itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout_text_card,parent,false);

            }else {

                itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout_text,parent,false);
            }

        //    View  itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout_text_card,parent,false);
            return new MyViewHolder(itemView);
        }else if(viewType == 3){  //纯图片，大于等于3张

            View  itemView;

            if(ConstrantManager.currentSystemid.equals("b30")){

                itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout_only_image_card,parent,false);

            }else {

                itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout_only_image,parent,false);
            }

      //      View  itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout_only_image,parent,false);
            return new MyViewHolder(itemView);
        }else if (viewType ==4){  //纯图片，2张

            View  itemView;

            if(ConstrantManager.currentSystemid.equals("b30")){

                itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout_only_image_two_card,parent,false);

            }else {

                itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout_only_image_two,parent,false);
            }

       //    View  itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout_only_image_two,parent,false);
            return new MyViewHolder(itemView);

        }else if (viewType ==5){ // 纯图片，1张

            View  itemView;

            if(ConstrantManager.currentSystemid.equals("b30")){

                itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout_only_image_one_card,parent,false);

            }else {

                itemView = LayoutInflater.from(mContext).inflate(R.layout.item_note_layout_only_image_one,parent,false);
            }


            return new MyViewHolder(itemView);
        }

        return null;

    }

    public List<NoteBean> getNoteList() {
        return noteList;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        //holder.tv_msg.setText(msgList.get(position));
        if (holder instanceof MyViewHolder){

            NoteBean bean =  noteList.get(position);

            if (mKeyword!=null && !mKeyword.equals("")){

                ((MyViewHolder)holder).tv_note_time.setText(StringUtil.highlight(mContext,bean.getNoteEditTime(),mKeyword));
                ((MyViewHolder)holder).tv_note_title.setText(StringUtil.highlight(mContext,Html.fromHtml(bean.getNoteTitle()).toString().trim(),mKeyword));
                ((MyViewHolder)holder).tv_note_source.setText(bean.getResourceName());
                ((MyViewHolder) holder).tv_note_content.setText(StringUtil.highlight(mContext, HtmlUtil.getTextFromHtml(bean.getNoteContent()),mKeyword));

            }else {

                ((MyViewHolder)holder).tv_note_time.setText(bean.getNoteEditTime());
                ((MyViewHolder)holder).tv_note_title.setText(Html.fromHtml(bean.getNoteTitle()).toString().trim());
                ((MyViewHolder)holder).tv_note_source.setText(bean.getResourceName());
                ((MyViewHolder) holder).tv_note_content.setText(Html.fromHtml(HtmlUtil.getTextFromHtml(bean.getNoteContent())).toString().trim());
            }

            switch (bean.getSubjectID()){
                case "S2-English":

                    ((MyViewHolder)holder).tv_note_source.setText("英语 | "+bean.getResourceName());

                    break;
                case "S1-English":


                    ((MyViewHolder)holder).tv_note_source.setText("英语 | "+bean.getResourceName());
                    break;
                case "S2-Biology":


                    ((MyViewHolder)holder).tv_note_source.setText("生物 | "+bean.getResourceName());
                    break;
                case "S2-Chemistry":

                    ((MyViewHolder)holder).tv_note_source.setText("化学 | "+bean.getResourceName());
                    break;
                case "S2-Chinese":


                    ((MyViewHolder)holder).tv_note_source.setText("语文 | "+bean.getResourceName());
                    break;
                case "S2-Geography":

                    ((MyViewHolder)holder).tv_note_source.setText("地理 | "+bean.getResourceName());
                    break;
                case "S2-History":

                    ((MyViewHolder)holder).tv_note_source.setText("历史 | "+bean.getResourceName());
                    break;
                case "S2-Maths":

                    ((MyViewHolder)holder).tv_note_source.setText("数学 | "+bean.getResourceName());
                    break;
                case "S2-Physics":


                    ((MyViewHolder)holder).tv_note_source.setText("物理 | "+bean.getResourceName());
                    break;
                case "S2-Politics":


                    ((MyViewHolder)holder).tv_note_source.setText("政治 | "+bean.getResourceName());
                    break;
                case "Other":

                    ((MyViewHolder)holder).tv_note_source.setText("其他 | "+bean.getResourceName());
                    break;

                default:

                    ((MyViewHolder)holder).tv_note_source.setText("全部 | "+bean.getResourceName());

                    break;
            }

            Log.e("bean.getIsKeyPoint()",bean.getIsKeyPoint()+"");
            Log.e("屏幕大小", ScreenUtils.getScreenWidth()+"");

            if (bean.getIsKeyPoint() == 1){

                ((MyViewHolder) holder).tv_note_title.setCompoundDrawablesRelativeWithIntrinsicBounds(null,null,mContext.getResources().getDrawable(R.mipmap.notetool_highlight_star),null);
            }else {

                ((MyViewHolder) holder).tv_note_title.setCompoundDrawables(null,null,null,null);
            }


            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mItemClickListener.onItemClick(position,holder.itemView);
                }
            });
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    mItemClickListener.onItemLongClick(position,holder.itemView);
                    return true;
                }
            });


            if (((MyViewHolder) holder).iv_note_image!=null){

                if (bean.getImageUrls() == null || bean.getImageUrls().size() == 0) {
                    //当ViewHolder复用的时候，如果当前返回的图片url为null，为了防止上一个复用的viewHolder图片
                    //遗留，要clear并且将图片设置为空。
                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_note_image);
                    ((MyViewHolder) holder).iv_note_image.setImageDrawable(null);
                    ((MyViewHolder) holder).iv_note_image.setTag(R.id.imageloader_uri, position);
                    return;
                }
                Object tag=((MyViewHolder) holder).iv_note_image.getTag(R.id.imageloader_uri);
                if (tag!=null&&(int) tag!= position) {
                    //如果tag不是Null,并且同时tag不等于当前的position。
                    //说明当前的viewHolder是复用来的
                    //Cancel any pending loads Glide may have for the view
                    //and free any resources that may have been loaded for the view.
                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_note_image);
                }
                String url = bean.getImageUrls().get(0);
                RoundedCorners roundedCorners= new RoundedCorners(15);
                //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
                RequestOptions options=RequestOptions.bitmapTransform(roundedCorners).transforms(new CenterCrop(),roundedCorners).override(510, 400).placeholder(R.mipmap.nototool_image_loading);
                Glide.with(mContext)
                        .load(url)
                        .apply(options)
                        .into(((MyViewHolder) holder).iv_note_image);
                //给ImageView设置唯一标记。
                ((MyViewHolder) holder).iv_note_image.setTag(R.id.imageloader_uri, position);


            }else if (((MyViewHolder) holder).iv_image3!=null){  //展示三张图片的纯图片笔记

                if (bean.getImageUrls() == null || bean.getImageUrls().size() == 0) {
                    //当ViewHolder复用的时候，如果当前返回的图片url为null，为了防止上一个复用的viewHolder图片
                    //遗留，要clear并且将图片设置为空。
                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_image3);
                    ((MyViewHolder) holder).iv_image3.setImageDrawable(null);
                    ((MyViewHolder) holder).iv_image3.setTag(R.id.imageloader_uri, position);

                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_image2);
                    ((MyViewHolder) holder).iv_image2.setImageDrawable(null);
                    ((MyViewHolder) holder).iv_image2.setTag(R.id.imageloader_uri, position);

                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_image1);
                    ((MyViewHolder) holder).iv_image1.setImageDrawable(null);
                    ((MyViewHolder) holder).iv_image1.setTag(R.id.imageloader_uri, position);
                    return;
                }

                Object tag=((MyViewHolder) holder).iv_image3.getTag(R.id.imageloader_uri);

                if (tag!=null&&(int) tag!= position) {
                    //如果tag不是Null,并且同时tag不等于当前的position。
                    //说明当前的viewHolder是复用来的
                    //Cancel any pending loads Glide may have for the view
                    //and free any resources that may have been loaded for the view.
                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_image3);
                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_image2);
                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_image1);
                }
                String url1 = bean.getImageUrls().get(0);
                String url2 = bean.getImageUrls().get(1);
                String url3 = bean.getImageUrls().get(2);
                RoundedCorners roundedCorners= new RoundedCorners(15);
                //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
                RequestOptions options=RequestOptions.bitmapTransform(roundedCorners).transforms(new CenterCrop(),roundedCorners).override(510, 400).placeholder(R.mipmap.nototool_image_loading);
                Glide.with(mContext)
                        .load(url3)
                        .apply(options)
                        .into(((MyViewHolder) holder).iv_image3);

                Glide.with(mContext)
                        .load(url2)
                        .apply(options)
                        .into(((MyViewHolder) holder).iv_image2);

                Glide.with(mContext)
                        .load(url1)
                        .apply(options)
                        .into(((MyViewHolder) holder).iv_image1);
                //给ImageView设置唯一标记。
                ((MyViewHolder) holder).iv_image3.setTag(R.id.imageloader_uri, position);
                ((MyViewHolder) holder).iv_image2.setTag(R.id.imageloader_uri, position);
                ((MyViewHolder) holder).iv_image1.setTag(R.id.imageloader_uri, position);

            }else if (((MyViewHolder) holder).iv_image2!=null){  //展示二张图片的纯图片笔记


                if (bean.getImageUrls() == null || bean.getImageUrls().size() == 0) {
                    //当ViewHolder复用的时候，如果当前返回的图片url为null，为了防止上一个复用的viewHolder图片
                    //遗留，要clear并且将图片设置为空。


                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_image2);
                    ((MyViewHolder) holder).iv_image2.setImageDrawable(null);
                    ((MyViewHolder) holder).iv_image2.setTag(R.id.imageloader_uri, position);

                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_image1);
                    ((MyViewHolder) holder).iv_image1.setImageDrawable(null);
                    ((MyViewHolder) holder).iv_image1.setTag(R.id.imageloader_uri, position);
                    return;
                }

                Object tag=((MyViewHolder) holder).iv_image2.getTag(R.id.imageloader_uri);

                if (tag!=null&&(int) tag!= position) {
                    //如果tag不是Null,并且同时tag不等于当前的position。
                    //说明当前的viewHolder是复用来的
                    //Cancel any pending loads Glide may have for the view
                    //and free any resources that may have been loaded for the view.
                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_image2);
                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_image1);
                }
                String url1 = bean.getImageUrls().get(0);
                String url2 = bean.getImageUrls().get(1);
                RoundedCorners roundedCorners= new RoundedCorners(15);
                //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
                RequestOptions options=RequestOptions.bitmapTransform(roundedCorners).transforms(new CenterCrop(),roundedCorners).override(510, 400).placeholder(R.mipmap.nototool_image_loading);

                Glide.with(mContext)
                        .load(url2)
                        .apply(options)
                        .into(((MyViewHolder) holder).iv_image2);

                Glide.with(mContext)
                        .load(url1)
                        .apply(options)
                        .into(((MyViewHolder) holder).iv_image1);
                //给ImageView设置唯一标记。

                ((MyViewHolder) holder).iv_image2.setTag(R.id.imageloader_uri, position);
                ((MyViewHolder) holder).iv_image1.setTag(R.id.imageloader_uri, position);

            }else if (((MyViewHolder) holder).iv_image1!=null){  //纯图片一张图片

                if (bean.getImageUrls() == null || bean.getImageUrls().size() == 0) {
                    //当ViewHolder复用的时候，如果当前返回的图片url为null，为了防止上一个复用的viewHolder图片
                    //遗留，要clear并且将图片设置为空。

                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_image1);
                    ((MyViewHolder) holder).iv_image1.setImageDrawable(null);
                    ((MyViewHolder) holder).iv_image1.setTag(R.id.imageloader_uri, position);
                    return;
                }

                Object tag=((MyViewHolder) holder).iv_image1.getTag(R.id.imageloader_uri);

                if (tag!=null&&(int) tag!= position) {
                    //如果tag不是Null,并且同时tag不等于当前的position。
                    //说明当前的viewHolder是复用来的
                    //Cancel any pending loads Glide may have for the view
                    //and free any resources that may have been loaded for the view.
                    Glide.with(mContext).clear(((MyViewHolder) holder).iv_image1);
                }
                String url1 = bean.getImageUrls().get(0);

                RoundedCorners roundedCorners= new RoundedCorners(15);
                //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
                RequestOptions options=RequestOptions.bitmapTransform(roundedCorners).transforms(new CenterCrop(),roundedCorners).override(510, 400).placeholder(R.mipmap.nototool_image_loading);


                Glide.with(mContext)
                        .load(url1)
                        .apply(options)
                        .into(((MyViewHolder) holder).iv_image1);
                //给ImageView设置唯一标记。

                ((MyViewHolder) holder).iv_image1.setTag(R.id.imageloader_uri, position);

            }



        }else if (holder instanceof TimeViewHolder){

            ((TimeViewHolder) holder).tv_time.setText(noteList.get(position).getTimeFlag());

        }
    }

    public void setScolling(boolean IsScrolling){

        mIsScrolling = IsScrolling;

    }

    public void removeItem(int position){
        noteList.remove(position);//删除数据源,移除集合中当前下标的数据

        notifyDataSetChanged();
     //   notifyItemRemoved(position);//刷新被删除的地方
     //   notifyItemRangeChanged(position,getItemCount()); //刷新被删除数据，以及其后面的数据
    }



    public void setKeyWord(String keyWord){

        mKeyword = keyWord;
    }


    @Override
    public int getItemCount() {
        return noteList.size() == 0?0:noteList.size()+1;
    }

    @Override
    public int getItemViewType(int position) {


        if (position == noteList.size()){  //foot

            return 1;

        }else if (noteList.get(position).isNormal()){  //normal

            if (noteList.get(position).getImageUrls()!=null&&noteList.get(position).getImageUrls().size()>0){

                NoteBean noteBean = noteList.get(position);

                if (HtmlUtil.getTextFromHtml(noteBean.getNoteContent()).trim().equals("")){  //纯图片笔记
                    if (noteBean.getImageUrls().size()>=3){  //展示3张图片的布局

                        return 3;

                    }

                    if (noteBean.getImageUrls().size() == 2){ //展示2张图片的布局

                        return 4;
                    }

                    if (noteBean.getImageUrls().size() == 1){ //展示1张图片的布局

                        return 5;
                    }

                }else {  //非纯文本

                    return 0;
                }

            }else {  //展示纯文本类型

                return 6;
            }


        }else {  //header

            return 2;
        }

        return 0;
    }


    public void addAll(List<NoteBean> list) {
        int lastIndex = this.noteList.size();
        if (this.noteList.addAll(list)) {

            notifyItemRangeInserted(lastIndex, list.size());  //局部更新

        }
    }

    public void resetDataList(List<NoteBean> noteBeans, RecyclerView mRecyclerView){
        this.noteList = noteBeans;
        // notifyDataSetChanged();
        //  mRecyclerView.getAdapter().notifyDataSetChanged();
        //   notifyDataSetChanged();
        final Context context = mRecyclerView.getContext();
        final LayoutAnimationController controller =
                AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down);

        mRecyclerView.setLayoutAnimation(controller);
        //  mRecyclerView.getAdapter().notifyDataSetChanged();
        notifyDataSetChanged();
        mRecyclerView.scheduleLayoutAnimation();
    }

    public void setDataList(List<NoteBean> noteList){

        this.noteList = noteList;
        notifyDataSetChanged();
    }

    public void removeAllItemFromDataList(){
        noteList.clear();
        notifyDataSetChanged();
    }

    public void setmCurrentSysName(String sysName){

        this.mCurrentSysName = sysName;
    }

    public void setItemClickListener(ItemClickListener ItemClickListener){
        this.mItemClickListener = ItemClickListener;
    }



    class MyViewHolder extends RecyclerView.ViewHolder{
        TextView tv_note_title,tv_note_source,tv_note_time,tv_note_content;
        ImageView iv_note_img,iv_key_img,iv_subject_small,iv_note_image,iv_image1,iv_image2,iv_image3;


        public MyViewHolder(View itemView) {
            super(itemView);
         //   iv_note_img = itemView.findViewById(R.id.iv_msg_img);
            tv_note_source = itemView.findViewById(R.id.tv_note_source);
            tv_note_time = itemView.findViewById(R.id.tv_note_time);
            tv_note_title = itemView.findViewById(R.id.tv_note_title);

            tv_note_content = itemView.findViewById(R.id.tv_note_content);
            iv_note_image = itemView.findViewById(R.id.iv_note_image);
         //   iv_key_img = itemView.findViewById(R.id.iv_keylearning_img);
        //    iv_subject_small = itemView.findViewById(R.id.iv_subject_small);
            iv_image1 = itemView.findViewById(R.id.iv_image1);
            iv_image2 = itemView.findViewById(R.id.iv_image2);
            iv_image3 = itemView.findViewById(R.id.iv_image3);

        }
    }


    class TimeViewHolder extends RecyclerView.ViewHolder{

        TextView tv_time;

        public TimeViewHolder(View itemView) {
            super(itemView);

            tv_time = itemView.findViewById(R.id.tv_time);

        }
    }

    public class FooterHolder extends RecyclerView.ViewHolder {
        RelativeLayout mLoadingViewstubstub;
        TextView mEndViewstub;
        TextView mNetworkErrorViewstub;

        public FooterHolder(View itemView) {
            super(itemView);
            mLoadingViewstubstub = itemView.findViewById(R.id.rl_loading);
            mEndViewstub = itemView.findViewById(R.id.tv_end);
            mNetworkErrorViewstub = itemView.findViewById(R.id.tv_error);
        }

        //根据传过来的status控制哪个状态可见
        public void setData(int status) {
            Log.d("TAG", "reduAdapter" + status + "");
            switch (status) {
                case 0:   //正常
                    setAllGone();
                    break;
                case 1:   //正在加载
                    setAllGone();
                    mLoadingViewstubstub.setVisibility(View.VISIBLE);
                    break;
                case 2:   //已全部加载
                    setAllGone();
                    mEndViewstub.setVisibility(View.VISIBLE);
                    break;
                case 3:   //网络出错
                    setAllGone();
                    mNetworkErrorViewstub.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
        }

        //全部不可见
        void setAllGone() {
            if (mLoadingViewstubstub != null) {
                mLoadingViewstubstub.setVisibility(View.GONE);
            }
            if (mEndViewstub != null) {
                mEndViewstub.setVisibility(View.GONE);
            }
            if (mNetworkErrorViewstub != null) {
                mNetworkErrorViewstub.setVisibility(View.GONE);
            }
        }

    }
}
